;
(function() {

	var _bind_state_arr;
	var _init_bind_state_arr = function() {
		_bind_state_arr = [];
		Object.keys(BusUserBindCon.STATE).forEach(function(key) {
			_bind_state_arr[BusUserBindCon.STATE[key]] = key;
		});
	};

	var skill = {
		save: function() {
			delete this.bus
			delete this.user
			delete this._money
			db.update(db_table_name, this._id, this);
		},
		destroy: function() {
			db.remove(db_table_name, this._id);
		},
		//非安全
		//在订单完成完整交易才返利
		//必须在BUFF中进行触发
		_addAchs: function(ach_id, acc) {
			var achs = this.achs || [];
			var ach = AchCon.get(ach_id);
			if (!ach) {
				throwCusError("找不到指定订单");
			}
			if (achs.indexOf(ach_id) === -1) {
				achs.unshift(ach_id);
				this.acc += parseFloat(acc) || 0;
				this.save();
			}
		},
		_nextFlowStatus: function() {
			var state = +this.state;
			console.log(state);
			if (state || state == 0) {
				if (!_bind_state_arr) {
					_init_bind_state_arr();
				}
				//如果有下一个状态值，进入
				if (_bind_state_arr[state + 1]) {
					state += 1;
				}
			} else {
				throwCusError("未知的兑现状态")
			}
			console.log(state);
			this.state = state;
			this.save();
			return state;
		},
		//非安全，将份额使用掉
		_useMoney: function(money_num) {
			//格式化
			money_num = parseFloat(money_num) || 0;
			if (money_num < 0) {
				throwCusError("使用的金额不可为负数")
			}
			var bus = BusCon.get(this.bus_id);
			//计算可用的抵消金额
			var _money = bus.recommendAccToMoney(this.acc);
			//上限校验
			if (money_num > _money) {
				throwCusError("可用金额不足")
			}
			var _acc = bus.recommendMoneyToAcc(money_num);
			console.log(this.acc, this.total_acc);
			this.acc -= _acc;
			this.total_acc += _acc;
			console.log(this.acc, this.total_acc);
			this.save();
		},
		//非安全，将积分额度转成到用户账户上的可用金额
		_to_BusUser_money: function(money_num) {
			//格式化
			money_num = parseFloat(money_num) || 0;
			if (money_num <= 0) {
				throwCusError("输入金额有误")
			}
			var bus = BusCon.get(this.bus_id);
			//计算抵消金额所需的积分
			var _acc = bus.recommendMoneyToAcc(money_num);
			//上限校验
			console.log(_acc, this.acc)
			if (_acc > this.acc) {
				throwCusError("可用金额不足")
			}
			console.log(this.acc, this.total_acc);
			this.acc -= _acc;
			this.total_acc += _acc;
			console.log(this.acc, this.total_acc);

			var bus_user = BusUserCon.get(BusUserCon.build(this));
			bus_user._addMoney(money_num);

			this.save();
		}
	};

	module.exports = skill;

	var db = require("../db/index");
	var config = require("../_include/config");
	var db_table_name = config.dbname.busUserBind;
	var db_id_prefix = config.dbIdPrefix.busUserBind;
	var UserCon = require("../user/_con");
	var BusCon = require("../bus/_con");
	var AchCon = require("../ach/_con");
	var BusUserBindCon = require("./_con");
	var BusUserCon = require("../bus_user/_con");

}());